import React from "react";
import { notification } from "antd";
import { MessageOutlined } from "@ant-design/icons";
import { isPlainObject } from "lodash";
import { childConfig } from "@/config";
import { auth } from "@/utils/T";

// const _notification = Object.assign({}, notification);
const prefixCls = `${childConfig.prefixCls}-notification`;

function convertNotificationArgs(args: any) {
  const config = { prefixCls };
  if (isPlainObject(args)) {
    Object.assign(config, args);
  } else {
    Object.assign(config, { description: args });
  }
  return config;
}

class _notification {
  public option: any = null;
  public tipDom: any = null;
  constructor() {
    notification.config({
      prefixCls,
      top: 84,
      duration: 3,
    });
    this.option = {
      maxCount: 2,
    };
    this.tipDom = document.querySelector(`.${prefixCls}`);
  }

  /**
   * 控制显示个数
   */
  update() {
    if (!auth.getToken()) {
      notification.destroy();
      return;
    }
    if (!this.tipDom) this.tipDom = document.querySelector(`.${prefixCls}`);
    if (this.tipDom) {
      try {
        const spanDom = this.tipDom.firstChild;
        const childNodes = spanDom.childNodes;
        if (childNodes.length > this.option.maxCount) {
          for (let i = 0; i < childNodes.length - this.option.maxCount; i++) {
            // spanDom.removeChild(childNodes[i])
            childNodes[i].style.display = "none"; // 此种方法降低操作dom造成的性能消耗
          }
        }
      } catch (e) {}
    }
  }

  success(config: any) {
    notification.success({
      message: "成功",
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  error(config: any) {
    notification.error({
      message: "错误",
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  info(config: any) {
    notification.info({
      message: "消息",
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  warning(config: any) {
    notification.warning({
      message: "警告",
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  warn(config: any) {
    notification.warning({
      message: "警告",
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  loading(config: any) {
    notification.open({
      message: "加载中",
      icon: (
        <MessageOutlined style={{ color: "#7C8995" }} type="loading" spin />
      ),
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  open(config: any) {
    notification.open({
      message: "通知",
      ...convertNotificationArgs(config),
    });
    this.update();
  }
}
export default new _notification();
